<?php

namespace App\Third\Service\Lsy;


use App\Common\Service\BaseService;
use App\Third\Model\ShopSchemeGoodsPriceModel;
use App\Third\Model\ShopSchemeModel;

class LsyShopGoodsPriceService extends BaseService
{
    public function getShopGoodsPrice(array $where)
    {
        return ShopSchemeGoodsPriceModel::query()->where($where)->first()->toArray();
    }

    public static function shopGoodsPriceDelete(array $where)
    {
        return ShopSchemeGoodsPriceModel::query()->where($where)->delete();
    }

    public function saveAll(array $data)
    {
        ShopSchemeGoodsPriceModel::query()->insert($data);
    }

    /**
     * 店铺 ==》方案 ==》商品 ==》 价格
     * @param string $lsy_shop_no
     * @param array|null $goods_crm_code
     * @return \Hyperf\Database\Model\Builder[]|\Hyperf\Database\Model\Collection|\Hyperf\Database\Query\Builder[]|\Hyperf\Utils\Collection
     * @author liule
     * @date 2021-01-26 9:14
     */
    public function shopGoodsPriceByScheme(string $lsy_shop_no, ?array $goods_crm_code){
        $sh = $this->container->get(ShopSchemeModel::class)->getTable();
        $spm = $this->container->get(ShopSchemeGoodsPriceModel::class);
        $sp = $spm->getTable();
        $filed = ['sp.crm_goods_id', 'sp.schemeID', 'sp.price', 'sp.stdPrice'];
        return $spm::from("{$sp} as sp")
            ->leftJoin("{$sh} as sh", 'sp.schemeID', '=', 'sh.schemeID')
            ->whereRaw('FIND_IN_SET(?,sh.shops)', [$lsy_shop_no])
            ->when($goods_crm_code, function ($query, $goods_crm_code){
                return $query->whereIn('sp.crm_goods_id', $goods_crm_code);
            })
            ->select($filed)
            ->get();
    }

    /**
     * 所有店铺方案价格
     * @param string|null $goods_crm_code
     * @return array
     * @author 1iu
     * @date 2021-02-07 14:57
     */
    public function getAllSchemePrice(?string $goods_crm_code = null){
        $sh = $this->container->get(ShopSchemeModel::class)->getTable();
        $spm = $this->container->get(ShopSchemeGoodsPriceModel::class);
        $sp = $spm->getTable();
        $filed = ['sh.shops', 'sp.crm_goods_id', 'sp.schemeID', 'sp.price', 'sp.stdPrice'];
        $ret = $spm::from("{$sp} as sp")
            ->leftJoin("{$sh} as sh", 'sp.schemeID', '=', 'sh.schemeID')
            ->when($goods_crm_code, function ($query, $goods_crm_code){
                return $query->where(['sp.crm_goods_id' => $goods_crm_code]);
            })
            ->select($filed)
            ->get()->toArray();
        $map = [];
        foreach ($ret as $k => $v){
            $map[$v['shops']][$v['crm_goods_id']] = ['schemeID'=>$v['schemeID'],'price'=>$v['price'],'stdPrice'=>$v['stdPrice']];
        }
        return $map;
    }

}
